package com.cgsd.heyu.ui.home;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Message;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.android.library.utils.SharedPreferencesHelper;
import com.android.library.utils.StringUtils;
import com.cgsd.heyu.R;
import com.cgsd.heyu.ad.AdListener;
import com.cgsd.heyu.ad.AdSplash;
import com.cgsd.heyu.common.AdConstants;
import com.cgsd.heyu.common.AppMobclickAgent;
import com.cgsd.heyu.common.CommonConfig;
import com.cgsd.heyu.common.Constants;
import com.cgsd.heyu.common.UserModeConfig;
import com.cgsd.heyu.entity.AdContentEntity;
import com.cgsd.heyu.entity.TabEntity;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.presenter.user.UserContract;
import com.cgsd.heyu.presenter.user.UserPresenter;
import com.cgsd.heyu.ui.BaseActivity;
import com.cgsd.heyu.ui.common.TabActivity;
import com.cgsd.heyu.ui.login.AvatarSelectActivity;
import com.cgsd.heyu.ui.login.LoginActivity;
import com.cgsd.heyu.utils.StatusBarUtil;
import com.cgsd.heyu.utils.WeakHandler;
import com.cgsd.heyu.widgets.dialog.PermissionDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaoxing
 * @description 启动页
 * @createData: 2020/11/2
 */
public class SplashActivity extends BaseActivity<UserContract.Presenter> implements WeakHandler.IHandler, UserContract.UserInfoView {
    /**
     * 启动时常设置
     */
    private static final int AD_TIME_OUT = 3000;
    private static final int MSG_GO_MAIN = 1;
    private final WeakHandler mHandler = new WeakHandler(this);

    /**
     * 所需要的动态权限
     * 1.相机权限
     * 2.存储权限
     * 3.位置权限
     * 4.麦克风权限
     * 5.设备信息权限
     */
    String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION};
    private List<String> mPermissionList = new ArrayList<>();
    private final int mRequestCode = 100;
    private FrameLayout mSplashContainer;
    /**
     * 是否已经到达最大设置时间
     */
    private boolean isMaxTime;
    /**
     * 开屏广告
     *
     * @return
     */
    private AdSplash adSplash;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initView() {
        AppMobclickAgent.onEvent(AppMobclickAgent.QIDONGYE);
        new UserPresenter(this);
        mSplashContainer = findViewById(R.id.splash_container);

        requestPermission();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void setStatusBar() {
        StatusBarUtil.fullNoBar(this);
    }

    @Override
    public void handleMsg(Message msg) {
        isMaxTime = true;
    }

    /**
     * 跳转下一个界面设置
     */
    private void nextActivity() {
//        LoginActivity.actionStart(this);
        if (UserModeConfig.getInstance().isLogin() && StringUtils.isEmpty(UserModeConfig.getInstance().headImgUrl)) {
            //如果登录了，没有选择头像，进入选择头像界面
            AvatarSelectActivity.actionStart(this, AvatarSelectActivity.CREATE_AVATAR);
        } else if (UserModeConfig.getInstance().isLogin()) {
//            MainActivity.actionStart(this);
            startActivity(TabActivity.getIntent(this));
        } else {
            LoginActivity.actionStart(this);
        }
        finish();
    }

    /**
     * 权限申请设置
     */
    private void requestPermission() {
        //逐个判断你要的权限是否已经通过
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                //添加还未授予的权限
                mPermissionList.add(permissions[i]);
            }
        }

        boolean isFirst = SharedPreferencesHelper.getBoolean(Constants.ShareKeyValue.IS_SHOW_PERMISSION);
        //申请权限
        if (mPermissionList.size() > 0 && !isFirst) {
            //有权限没有通过，并且是第一次申请权限，给出弹窗说明
            SharedPreferencesHelper.put(Constants.ShareKeyValue.IS_SHOW_PERMISSION, true);
            showPermissionDialog();
        } else if (mPermissionList.size() > 0) {
            //有权限没有通过,不是第一次申请权限，直接申请权限
            ActivityCompat.requestPermissions(SplashActivity.this, permissions, mRequestCode);
        } else {
            //权限都通过的情况（直接倒计时进入）
            mHandler.sendEmptyMessageDelayed(MSG_GO_MAIN, AD_TIME_OUT);
            if (UserModeConfig.getInstance().isLogin()) {
                mPresenter.getUserInfo();
            } else {
                nextActivity();
            }
        }
    }

    /**
     * 请求权限后回调的方法
     * requestCode  是我们自己定义的权限请求码
     * permissions  是我们请求的权限名称数组
     * grantResults 是我们在弹出页面后是否允许权限的标识数组，数组的长度对应的是权限名称数组的长度，数组的数据0表示允许权限，-1表示我们点击了禁止权限
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (UserModeConfig.getInstance().isLogin()) {
            mPresenter.getUserInfo();
        } else {
            nextActivity();
        }
    }

    /**
     * 申请权限提示
     */
    private void showPermissionDialog() {
        List<TabEntity> data = new ArrayList<>();
        for (String permission : mPermissionList) {
            switch (permission) {
                //相机权限
                case Manifest.permission.CAMERA:
                    data.add(new TabEntity(R.mipmap.ic_popup_camera, getString(R.string.permission_camera), getString(R.string.permission_camera_tips)));
                    break;
                //存储权限
                case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                    data.add(new TabEntity(R.mipmap.ic_popup_storage, getString(R.string.permission_save), getString(R.string.permission_save_tips)));
                    break;
                //位置权限
                case Manifest.permission.ACCESS_COARSE_LOCATION:
                    data.add(new TabEntity(R.mipmap.ic_popup_position, getString(R.string.permission_position), getString(R.string.permission_position_tips)));
                    break;
                //麦克风权限
                case Manifest.permission.RECORD_AUDIO:
                    data.add(new TabEntity(R.mipmap.ic_popup_voice, getString(R.string.permission_microphone), getString(R.string.permission_microphone_tips)));
                    break;
                //设备信息权限
                case Manifest.permission.READ_PHONE_STATE:
                    data.add(new TabEntity(R.mipmap.ic_popup_device, getString(R.string.permission_equipment), getString(R.string.permission_equipment_tips)));
                    break;
                default:
            }
        }
        PermissionDialog dialog = new PermissionDialog(this, data);
        dialog.setOnDialogListener(new PermissionDialog.OnDialogListener() {
            @Override
            public void confirm() {
                dialog.dismiss();
                ActivityCompat.requestPermissions(SplashActivity.this, permissions, mRequestCode);
            }
        });
        dialog.show();
    }

    @Override
    public void infoSuccess(UserModeConfig userModeConfig) {
        mPresenter.getConfigInfo(null, 100);
    }

    @Override
    public void setConfig(String sysType) {
        if (CommonConfig.getInstance().isShowAd) {
            mPresenter.getAdContent(AdConstants.SPLASH);
        } else {
            nextActivity();
        }

    }

    @Override
    public void setAdContent(AdContentEntity entity) {
        if (entity == null || isMaxTime) {
            nextActivity();
            return;
        }
        adSplash = new AdSplash(this, entity, mSplashContainer, adListener);
        adSplash.loadAd();
    }

    private AdListener adListener = new AdListener() {

        @Override
        public void onSuccess() {
            super.onSuccess();
            dismissCommonSubmitDialog();
        }

        @Override
        public void onFail() {
            super.onFail();
            dismissCommonSubmitDialog();
            nextActivity();
        }

        @Override
        public void onVideoComplete() {
            super.onVideoComplete();
            dismissCommonSubmitDialog();
            nextActivity();
        }
    };

    @Override
    public void setErrorMessage(ErrorMessage error) {
        //如果出现错误，统一跳转到登陆页面,这里错误不能清空数据
        showToast(error.getMessage());
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }
}
